import Axios from 'axios'
import Qs from 'qs'

const waringMsg = '数据服务通信异常'
Axios.defaults.baseURL = process.env.BASE_URL
Axios.defaults.timeout = -1
Axios.defaults.withCredentials = true

/*
 * @description: 统一网络错误处理
 * @param {type}
 * @return:
 */
function catchError (e) {
  if (e.message !== 'Network Error') {
    window.Toast.error(waringMsg)
    return Promise.reject(new Error(waringMsg))
  }
  return Promise.reject(new Error('NETWORK_ERROR'))
}
/*
 * @description: 处理请求
 * @param {type}
 * @return:
 */
async function request (config) {
  try {
    if (!config.headers) {
      config.headers = {}
    }
    const res = await Axios(config)
    return res
  } catch (e) {
    return catchError(e)
  }
}

export default {
  get (url, params, customConfig = {}) {
    const config = {
      url,
      params,
      method: 'get',
      ...customConfig,
    }

    return request(config)
  },
  post (url, data, customConfig = { }) {
    const config = {
      url,
      data,
      method: 'post',
      transformRequest: [
        function (data) {
          return Qs.stringify(data)
        },
      ],
      ...customConfig,
    }

    return request(config)
  },
  upload (url, formData, customConfig = {}) {
    return Axios.post(url, formData, { headers: { 'Content-Type': 'multipart/form-data' }, ...customConfig })
  },
  postJson (url, param, customConfig = {}) {
    const config = {
      url,
      data: param,
      method: 'post',
      headers: { 'Content-Type': 'application/json' },
      ...customConfig,
    }

    return request(config)
  },
}
